package com.longge;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-05-05 03:26
 */
public class CombinationSum3 {
    ArrayList<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        ArrayList<Integer> path = new ArrayList<>();
        int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        backtrack(candidates, 0, n, path, k);
        return res;
    }

    private void backtrack(int[] candidates, int start, int target, ArrayList<Integer> path, int k) {
        if (target == 0 && path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (target!= 0 && path.size() == k) {
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            target -= candidates[i];
            if (target < 0) return;
            path.add(candidates[i]);
            backtrack(candidates, i+1, target, path, k);
            path.remove(path.size() - 1);
            target += candidates[i];
        }
    }

}
